import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, Form, Input, Select, Button, InputNumber, Modal, message, Radio } from 'antd';
import RecommendTable from '../../../components/Huishuaka/Config/Recommend';
import PageHeaderLayout from '../../../layouts/PageHeaderLayout';

import styles from './Recommend.less';

let isAdd = true;
const FormItem = Form.Item;
const smartTypes = RecommendTable.smartTypes
const { TextArea } = Input;
const { Option } = Select;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(({ recommend, loading }) => ({
  recommend,
  loading: loading.models.recommend,
}))
@Form.create()
export default class RecommendList extends PureComponent {
  state = {
    addInputValue: {},
    modalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
  };

  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'recommend/fetch',
    });

    console.log('--------我应该在render初始化之前执行');
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'recommend/fetch',
      payload: params,
    });
  }

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'recommend/fetch',
      payload: {},
    });
  }

  toggleForm = () => {
    this.setState({
      expandForm: !this.state.expandForm,
    });
  }

  deleteSelectClick = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    const that = this;

    Modal.confirm({
      title: '删除警告!',
      content: '确认删除所选内容？',
      onOk() {
        dispatch({
          type: 'recommend/remove',
          payload: {
            smart_id: `${selectedRows.map(row => row.smart_id).join(',')},`,
          },
          callback: () => {
            that.setState({
              selectedRows: [],
            });
          },
        });
      },
      onCancel() {
        // alert(JSON.stringify(selectedRows));
      },
    });
  }

  handleMenuClick = (e) => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;

    if (!selectedRows) return;

    switch (e.key) {
      case 'remove':
        dispatch({
          type: 'recommend/remove',
          payload: {
            no: selectedRows.map(row => row.no).join(','),
          },
          callback: () => {
            this.setState({
              selectedRows: [],
            });
          },
        });
        break;
      default:
        break;
    }
  }

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  }

  handleSearch = (e) => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'recommend/fetch',
        payload: values,
      });
    });
  }

  addOne = () => {
    this.clearForm();
    isAdd = true;
    this.handleModalVisible(true);
  }

  clearForm = () => {
    if (!isAdd) { // 清除表单内容
      this.state.addInputValue = {}; // 清除上一次加载的行数据——阻止编辑时的数据进入新增页面表单
      this.props.form.resetFields(); // 清除当前表单的数据——阻止编辑时未存储的数据进入1个新的编辑页
    }
  }

  handleModalVisible = (flag) => {
    this.setState({
      modalVisible: !!flag,
    });
  }

  // 通过代理对象传入控件value
  handleAddInput = (e) => {
    let key = e.target.id;
    if (!key) {
      key = e.target.name;
    }
    this.state.addInputValue[key] = e.target.value;
  }

  // 直接传入控件value
  addInputNumber = (val) => {
    this.state.addInputValue.smart_order = val;
  }
  addInputSelect = (val) => {
    this.state.addInputValue.smart_property = val;
  }

  // 修改
  modifyOne = (row) => {
    this.clearForm();
    isAdd = false;
    this.state.addInputValue = JSON.parse(JSON.stringify(row));// 防止传递引用
    this.handleModalVisible(true);
  }
  // 上下架
  modifyShow = (row) => {
    this.state.addInputValue = JSON.parse(JSON.stringify(row));// 防止传递引用
    const desc = row.smart_show === 0 ? '上' : '下';
    this.handleAdd(`${desc}架成功`);
  }

  handleAdd = (desc) => {
    const callbackFuc = (response) => {
      let d = desc;
      if (!d) {
        d = '添加成功';
      }
      if (!response || response.code !== '1') {
        message.error('添加失败');
      } else {
        message.success(d);
        this.setState({
          modalVisible: false,
        });
        this.state.addInputValue = {};
      }
    }
    this.props.dispatch({
      type: 'recommend/add',
      payload: this.state.addInputValue,
      callback: callbackFuc,
    });
  }

  /*  renderSimpleForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="规则编号">
              {getFieldDecorator('no')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">查询</Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <Icon type="down" />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  } */

  /*  renderAdvancedForm() {
    const { getFieldDecorator } = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="规则编号">
              {getFieldDecorator('no')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="调用次数">
              {getFieldDecorator('number')(
                <InputNumber style={{ width: '100%' }} />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="更新日期">
              {getFieldDecorator('date')(
                <DatePicker style={{ width: '100%' }} placeholder="请输入更新日期" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status3')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="使用状态">
              {getFieldDecorator('status4')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="0">关闭</Option>
                  <Option value="1">运行中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button type="primary" htmlType="submit">查询</Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
            <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
              收起 <Icon type="up" />
            </a>
          </span>
        </div>
      </Form>
    );
  } */

  /*  renderForm() {
    return this.state.expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  } */

  render() {
    const { recommend: { data }, loading } = this.props;
    const { selectedRows, modalVisible, addInputValue } = this.state;
    const { getFieldDecorator, validateFieldsAndScroll, getFieldValue } = this.props.form;

    const validate = () => {
      validateFieldsAndScroll((error) => {
        if (!error) {
          // submit the values
          this.handleAdd();
        }
      });
    };

    return (
      <PageHeaderLayout title="智能推荐选项设置">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.addOne()}>
                新建
              </Button>
              {
                selectedRows.length > 0 && (
                  <span>
                    <Button onClick={this.deleteSelectClick}>批量删除</Button>
                    {/* <Dropdown overlay={menu}>
                      <Button>
                        更多操作 <Icon type="down" />
                      </Button>
                    </Dropdown> */}
                  </span>
                )
              }
            </div>
            <RecommendTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              modifyOne={this.modifyOne}
              modifyShow={this.modifyShow}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        <Modal
          title="添加智能推荐配置"
          visible={modalVisible}
          onOk={validate}
          onCancel={() => this.handleModalVisible()}
        >
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="匹配项"
          >
            {getFieldDecorator('smart_type', {
              initialValue: this.state.addInputValue.smart_type,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <Input placeholder="匹配项" id="smart_type" onChange={this.handleAddInput} />
            )}
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="选择项"
          >
            {getFieldDecorator('smart_option', {
              initialValue: this.state.addInputValue.smart_option,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <TextArea style={{ minHeight: 32 }} id="smart_option" placeholder="选择项" rows={4} onChange={this.handleAddInput} />
            )}
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="排序"
          >
            {getFieldDecorator('smart_order', {
              initialValue: this.state.addInputValue.smart_order,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <InputNumber id="smart_order" placeholder="排序" min={0} max={100} onChange={this.addInputNumber} />
            )}
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="上下架"
          >
            {getFieldDecorator('smart_show', {
              initialValue: this.state.addInputValue.smart_show,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <Radio.Group name="smart_show" onChange={this.handleAddInput}>
                <Radio value={0}>上架</Radio>
                <Radio value={1}>下架</Radio>
              </Radio.Group>
            )}
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="控件"
          >
            {getFieldDecorator('smart_muiti', {
              initialValue: this.state.addInputValue.smart_muiti,
              rules: [
                {
                  required: true,
                  message: '这是一个必填项！',
                },
              ],
            })(
              <Radio.Group name="smart_muiti" onChange={this.handleAddInput}>
                <Radio value={1001}>文本</Radio>
                <Radio value={1002}>地址选择框</Radio>
                <Radio value={1004}>单选</Radio>
              </Radio.Group>
            )}
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="匹配认证项"
          >
            <Select
              id="smart_property"
              onSelect={this.addInputSelect}
              placeholder="不限"
              defaultValue={this.state.addInputValue.smart_property}
              style={{ maxWidth: 200, width: '100%' }}
            >
              {
                smartTypes.map(type =>
                  <Option value={type.value}>{type.text}</Option>
                )
              }
            </Select>
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="规则"
          >
            <Input placeholder="规则" id="smart_rule" onChange={this.handleAddInput} value={this.state.addInputValue.smart_rule} />
          </FormItem>
          <FormItem
            labelCol={{ span: 5 }}
            wrapperCol={{ span: 15 }}
            label="规则说明"
          >
            <Input placeholder="规则说明" id="smart_rule_desc" onChange={this.handleAddInput} value={this.state.addInputValue.smart_rule_desc} />
          </FormItem>
        </Modal>
      </PageHeaderLayout>
    );
  }
}
